package com.building.hcrm.ui.customer;

import java.util.ArrayList;
import java.util.List;

import javax.security.auth.PrivateCredentialPermission;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.building.hcrm.R;
import com.building.hcrm.R.id;
import com.building.hcrm.R.string;
import com.building.hcrm.base.BaseActivity;
import com.building.hcrm.common.ComConst;
import com.building.hcrm.common.ComFunc;
import com.building.hcrm.common.User;
import com.building.hcrm.model.CustomerDetail;
import com.building.hcrm.model.CustomerQuery;
import com.building.hcrm.model.CustomerQueryByPhoneParam;
import com.building.hcrm.wcf.CustomerServiceProxy;

/**
 * 客户管理主界面
 * 
 * @author hby
 * 
 */
public class CustomerMainActivity extends BaseActivity {
	private LinearLayout llAddCustomer = null;
	private ImageButton igmBtnSave;
	private EditText etSearch;
	private ListView customerListView;
	private CustomerDetailAdapter customerDetailAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_customer);
		initControls();
		initDatas();
		setOnAllListeners();
	}

	/**
	 * 初始化界面控件
	 */
	private void initControls() {
		llAddCustomer = (LinearLayout) findViewById(id.linear_search_customer);
		customerListView = (ListView) findViewById(id.lv_customer);
		etSearch = (EditText) findViewById(id.et_search_customer);
		imgbtnHome = (ImageButton) findViewById(id.imgbtn_home);
		imgbtnHome.setVisibility(View.VISIBLE);
		igmBtnSave = (ImageButton) findViewById(id.imgbtn_save);
		igmBtnSave.setVisibility(View.VISIBLE);
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		if (!("").equals(etSearch.getText().toString())) {
			llAddCustomer.performClick();
		}
	}
	/**
	 * 初始化界面数据
	 */
	private void initDatas() {
		setTitle(getResources().getString(string.customer_title_main));
	}

	private void setOnAllListeners() {
		llAddCustomer.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (User.getInstance(CustomerMainActivity.this).getUserNum() != null
						&& !("").equals(User.getInstance(
								CustomerMainActivity.this).getUserNum())) {
					CustomerQueryByPhoneParam cqb = new CustomerQueryByPhoneParam();
					cqb.customerPhone = etSearch.getText().toString();
					cqb.userNum = User.getInstance(getApplicationContext())
							.getUserNum();
					GetCustomerInfo getCustomerInfo = new GetCustomerInfo();
					getCustomerInfo.execute(cqb);
				} else {
					Toast.makeText(getApplicationContext(), "请先登录",
							Toast.LENGTH_SHORT).show();
				}
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

				imm.hideSoftInputFromWindow(etSearch.getWindowToken(), 0);
			}
		});

		imgbtnHome.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// getDatas();
				finish();
				slideReturnActivity();
			}
		});

		igmBtnSave.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (User.getInstance(getApplicationContext()).getUserNum() != null
						&& !("").equals(User.getInstance(
								getApplicationContext()).getUserNum())) {
					Intent intent = new Intent(getApplicationContext(),
							CustomerEditActivity.class);
					startActivity(intent);
					// 新Activity从右边滑到屏幕上，旧界面从屏幕上滑到左边
					slideNewActivity();
				} else {
					Toast.makeText(getApplicationContext(), "请先登录",
							Toast.LENGTH_SHORT).show();
				}
			}
		});
	}

	
	/**
	 * 
	 * @author MyPC
	 * 
	 */
	public class CustomerDetailAdapter extends BaseAdapter {
		private List<CustomerQuery> mCustomerList = null;
		private Context mContext;
		private int mLayout;
		private LayoutInflater mInflater;

		public CustomerDetailAdapter(Context context, List<CustomerQuery> list,
				int layoutId) {
			mCustomerList = list;
			mContext = context;
			mLayout = layoutId;
			mInflater = (LayoutInflater) mContext
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public int getCount() {
			if (mCustomerList != null) {
				return mCustomerList.size();
			} else {
				return 0;
			}
		}

		@Override
		public Object getItem(int position) {
			if (mCustomerList != null) {
				return mCustomerList.get(position);
			}
			return null;
		}

		public void setCustomerList(List<CustomerQuery> list) {
			mCustomerList = list;
			notifyDataSetChanged();
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder = null;
			if (convertView == null) {
				viewHolder = new ViewHolder();
				convertView = mInflater.inflate(mLayout, null);
				viewHolder.tvCustomerName = (TextView) convertView
						.findViewById(id.tv_customer_name);
				viewHolder.tvStatus = (TextView) convertView
						.findViewById(id.tv_status);
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			final CustomerQuery cDetail = mCustomerList.get(position);

			viewHolder.tvCustomerName
					.setText(cDetail.CustomerDetail.CustomerName);
			if (cDetail.Tag.equals("3") || cDetail.Tag.equals("5")) {
				viewHolder.tvStatus.setText(getResources().getString(
						R.string.customer_status_not));
			} else if (cDetail.Tag.equals("4")) {
				viewHolder.tvStatus.setText(getResources().getString(
						R.string.customer_status_pass));
			}
			// 3不能都能查看，绑定点击事件
			convertView.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent(CustomerMainActivity.this,
							CustomerEditActivity.class);
					intent.putExtra(ComConst.CUSTOMER_DATAS, cDetail);
					startActivity(intent);
					slideNewActivity();
				}
			});

			convertView.setTag(viewHolder);
			return convertView;
		}

		public class ViewHolder {
			public ImageView ivStatus;
			public TextView tvCustomerName;
			public TextView tvStatus;
		}
	}

	/**
	 * 获取客户信息异步类
	 * 
	 * @author MyPC
	 * 
	 */
	private class GetCustomerInfo
			extends
				AsyncTask<Object, Object, CustomerQuery> {
		private ProgressDialog pd;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			try {
				pd = new ProgressDialog(CustomerMainActivity.this);
				pd.setMessage("提交中...");
				pd.setIndeterminate(false);
				pd.setCancelable(false);
				pd.show();
			} catch (Exception e) {
				Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
			}
		}

		@Override
		protected CustomerQuery doInBackground(Object... arg0) {
			CustomerQuery result = null;
			try {
				if (null != arg0 && arg0.length > 0) {
					result = CustomerServiceProxy.getInstance(
							CustomerMainActivity.this).CustomerDetailByPhone(
							(CustomerQueryByPhoneParam) arg0[0]);
				}
			} catch (Exception e) {
				Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
			}
			return result;
		}

		@Override
		protected void onPostExecute(CustomerQuery result) {
			super.onPostExecute(result);
			pd.cancel();
			// 1：未知错误，2：无权查看，3：归属记录尚未通过审核，4：正常，5：客户信息尚未通过审核，6：客户信息不存在
			if (result.Tag.equals("4") || result.Tag.equals("3")
					|| result.Tag.equals("5")) {
				List<CustomerQuery> list = new ArrayList<CustomerQuery>();
				list.add(result);
				customerDetailAdapter = new CustomerDetailAdapter(
						getApplicationContext(), list,
						R.layout.item_customer_list);
				customerListView.setAdapter(customerDetailAdapter);
			} else {
				Toast.makeText(getApplicationContext(), result.Message,
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			imgbtnHome.performClick();
		}
		return false;
	}

}
